package ar.com.photo_admin.service.security

import grails.plugins.springsecurity.SpringSecurityService
import org.springframework.security.authentication.AuthenticationProvider
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.core.authority.GrantedAuthorityImpl
import org.springframework.security.core.userdetails.UserDetailsService

class EmailAuthenticationProvider implements AuthenticationProvider {

	SpringSecurityService springSecurityService
	PhotoAdminUserDetailsService userDetailsService

	Authentication authenticate(Authentication authentication) {
		def user = userDetailsService.loadUserByEmail(authentication.principal)

		if (user) {
			if (user?.password == springSecurityService.encodePassword(authentication.credentials)) {
				def token = new UsernamePasswordAuthenticationToken(user.username, user.password, user.authorities)
				token.details = authentication.details
				return token
			} else
				throw new BadCredentialsException("Incorrect password for user: " + user.username)
		} else
			return null
	}

	boolean supports(Class authentication) {
		return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)
	}
}
